package com.dingding.study.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingding.study.entity.CategoryEntity;
import com.dingding.study.mapper.CategoryMapper;
import com.dingding.study.service.CategoryService;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liugongding
 * @description:
 * @date 2022/9/19 9:24 PM
 */

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        //2、组装父子树形结构
        //2.1找到所有一级分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> menus = categoryEntities.stream()
                //一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                //找到当前菜单的子菜单
                .peek((menu) -> menu.setChildren(getChildrens(menu, categoryEntities)))
                .sorted(Comparator.comparingInt(menu -> menu.getSort() == null ? 0 : menu.getSort()))
                .collect(Collectors.toList());
        return menus;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity rootMenu, List<CategoryEntity> allEntites) {
        List<CategoryEntity> children = allEntites.stream()
                //如果当前菜单的id等于它的上级i,说明属于上下级关系
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(rootMenu.getCatId()))
                .peek((menu) -> menu.setChildren(getChildrens(menu, allEntites)))
                //递归查找，子菜单为空的话，排序会报空指针
                .sorted(Comparator.comparingInt(menu -> menu.getSort() == null ? 0 : menu.getSort()))
                .collect(Collectors.toList());
        return children;
    }

    public static void main(String[] args) {
        String[] strings = new String[0];
        String[] list = Lists.newArrayList("12").toArray(new String[0]);
    }
}
